#include "PreComplied.h"
#include "FileSys.h"

XFileSys::XFileSys()
{
	AddPath("./");
	AddSufix(".lua");
	AddSufix(".txt");
	AddPath("./../Resource");
}

XFileSys::~XFileSys()
{
}

XFile* XFileSys::OpenFile(const char* const fileName)
{

	FILE* pFile = fopen(fileName, "rb");
	if(pFile) return new XFile(pFile);
	for(iterator iter = m_paths.begin(); iter != m_paths.end(); ++iter)
	{
		std::string fullPath = *iter + fileName;
		pFile = fopen(fullPath.c_str(), "rb");
		if(pFile)
			return new XFile(pFile);
		for(iterator subIter = m_sufixs.begin(); subIter != m_sufixs.end(); ++subIter)
		{
			std::string tempPath = fullPath + *subIter;
			pFile = fopen(tempPath.c_str(), "rb");
			if(pFile)
				return new XFile(pFile);
		}
	}
	return NULL;
}

void XFileSys::CloseFile(XFile* pFile)
{
	delete pFile;
}

bool XFileSys::AddPath(const char* const path)
{
	std::string tempPath = path;
	if(tempPath[tempPath.size() - 1] != '/' && tempPath[tempPath.size() - 1] != '\\')
		tempPath += "/";
	for(iterator iter = m_paths.begin(); iter != m_paths.end(); ++iter)
	{
		if(*iter == tempPath)
			return false;
	}
	m_paths.push_back(tempPath);
	return true;
}

bool XFileSys::AddSufix(const char* const sufix)
{
	for(iterator iter = m_sufixs.begin(); iter != m_sufixs.end(); ++iter)
	{
		if(*iter == sufix)
			return false;
	}
	m_sufixs.push_back(sufix);
	return true;
}

